package com.shensi.adminCollect.controller.station;

import com.shensi.adminCollect.common.constant.Constants;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.common.redis.service.RedisCache;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.station.StationDeviceManage;
import com.shensi.adminCollect.service.station.IStationDeviceManageService;
import com.shensi.adminCollect.service.station.StationDeviceAudioService;
import com.shensi.adminCollect.utils.station.Methods;
import com.shensi.adminCollect.domain.system.SysStationUser;
import com.shensi.adminCollect.service.system.ISysStationUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;

/**
 * 油站设备管理Controller
 *
 * @author qujia
 * @date 2021-01-13
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/station/manage")
@Api(tags = "StationDeviceManageController", description = "设备管理")
public class StationDeviceManageController extends BaseController
{
    @Autowired
    private IStationDeviceManageService stationDeviceManageService;
    @Autowired
    private ISysStationUserService stationUserService;

    @Autowired
    private RedisCache redisCache;

    @Resource
    private StationDeviceAudioService stationDeviceAudioService;

    /**
     * 查询油站设备管理列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "设备列表",notes = "示例：https://yftx-test.xailife.com/prod-api/station/manage/list?pageNum=1&pageSize=10&deviceSerialNum=123&likeDeviceNo=123")
    public TableDataInfo list(StationDeviceManage stationDeviceManage)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        if("1".equals(currentUser.getUser().getUserLevel())){
            List<String> sta=new ArrayList<>();
            SysStationUser stationUser=new SysStationUser();
            stationUser.setEnterpriseId(currentUser.getUser().getEnterpriseId());
            List<SysStationUser> stationUsers=stationUserService.selectSysStationUserList(stationUser);
            for(SysStationUser sysStationUser:stationUsers){
                sta.add(sysStationUser.getStationId()+"");
            }
            if(stationUsers!=null&&stationUsers.size()>0) {
                stationDeviceManage.setStationIdList(sta);
            }else {
                stationDeviceManage.setStationId(0L);
            }
        }else if("2".equals(currentUser.getUser().getUserLevel())){
            stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        }
        /*SysDept dept =new SysDept();
        dept.setDeptId(currentUser.getUser().getStationId());
        List<String> list = deptService.selectDeptId(dept);
        if(list!=null && list.size()>0){
            stationDeviceManage.setStationIdList(list);
            stationDeviceManage.setStationId(null);
        }*/

        startPage();
        List<StationDeviceManage> manageList = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
        for(StationDeviceManage stationDeviceManage1:manageList){
            if(stationDeviceManage1.getUserIds()!=null&&!"".equals(stationDeviceManage1.getUserIds())){
                stationDeviceManage1.setUserIdList(Arrays.asList(stationDeviceManage1.getUserIds().split(",")));
            }else {
                stationDeviceManage1.setUserIdList(new ArrayList<>());
            }

            if("3".equals(stationDeviceManage1.getDeviceType()) && "1".equals(stationDeviceManage1.getDeviceFactory())){

                Object acceccTokenObj = redisCache.getCacheObject(Constants.DEVICE_CLIENT_TOKEN + stationDeviceManage1.getClientId());
                String token = "";
                if(Objects.isNull(acceccTokenObj)){
                    Methods m= Methods.getInstance();
                    m.init(stationDeviceManage1.getClientId(), stationDeviceManage1.getClientSecret());
                    String freedomToken = m.getFreedomToken();
//                    JSONObject json = new JSONObject(freedomToken);
//
//                    JSONObject body = json.getJSONObject("body");
//                    token = body.getString("access_token");
                    redisCache.setCacheObject(Constants.DEVICE_CLIENT_TOKEN + stationDeviceManage1.getClientId(),freedomToken,30, TimeUnit.DAYS);

                }else {
                    token = acceccTokenObj.toString();
                }
                stationDeviceManage1.setAccessToken(token);
            }
        }
        return getDataTable(manageList);
    }

    /**
     * 查询油站设备管理列表
     */
    @GetMapping("/feieList")
    public TableDataInfo feieList(StationDeviceManage stationDeviceManage)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        if("1".equals(currentUser.getUser().getUserLevel())){
            List<String> sta=new ArrayList<>();
            SysStationUser stationUser=new SysStationUser();
            stationUser.setEnterpriseId(currentUser.getUser().getEnterpriseId());
            List<SysStationUser> stationUsers=stationUserService.selectSysStationUserList(stationUser);
            for(SysStationUser sysStationUser:stationUsers){
                sta.add(sysStationUser.getStationId()+"");
            }
            if(stationUsers!=null&&stationUsers.size()>0) {
                stationDeviceManage.setStationIdList(sta);
            }else {
                stationDeviceManage.setStationId(0L);
            }
        }else if("2".equals(currentUser.getUser().getUserLevel())){
            stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        }
        /*SysDept dept =new SysDept();
        dept.setDeptId(currentUser.getUser().getStationId());
        List<String> list = deptService.selectDeptId(dept);
        if(list!=null && list.size()>0){
            stationDeviceManage.setStationIdList(list);
            stationDeviceManage.setStationId(null);
        }*/
        stationDeviceManage.setDeviceType("3");
        startPage();
        List<StationDeviceManage> manageList = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
        for(StationDeviceManage stationDeviceManage1:manageList){
            if(stationDeviceManage1.getUserIds()!=null&&!"".equals(stationDeviceManage1.getUserIds())){
                stationDeviceManage1.setUserIdList(Arrays.asList(stationDeviceManage1.getUserIds().split(",")));
            }else {
                stationDeviceManage1.setUserIdList(new ArrayList<>());
            }
        }
        return getDataTable(manageList);
    }

    /**
     * 导出油站设备管理列表
     */
    @GetMapping("/export")
    public AjaxResult export(StationDeviceManage stationDeviceManage)
    {

        LoginUser currentUser = SecurityUtils.getLoginUser();

        /*SysDept dept =new SysDept();
        dept.setDeptId(currentUser.getUser().getDeptId());
        List<String> list = deptService.selectDeptId(dept);
        if(list!=null && list.size()>0){
            stationDeviceManage.setStationIdList(list);
            stationDeviceManage.setStationId(null);
        }*/
        stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        List<StationDeviceManage> manageList = stationDeviceManageService.selectStationDeviceManageList(stationDeviceManage);
        ExcelUtil<StationDeviceManage> util = new ExcelUtil<StationDeviceManage>(StationDeviceManage.class);
        return util.exportExcel(manageList, "manage");
    }

    /**
     * 获取油站设备管理详细信息
     */
    @GetMapping(value = "/{deviceId}")
    public AjaxResult getInfo(@PathVariable("deviceId") Long deviceId)
    {
        return AjaxResult.success(stationDeviceManageService.selectStationDeviceManageById(deviceId));
    }

    /**
     * 新增油站设备管理
     */
    @ApiOperation("新增设备")
    @PostMapping
    public AjaxResult add(@RequestBody @Valid StationDeviceManage stationDeviceManage) throws Exception {
//        LoginUser currentUser = SecurityUtils.getLoginUser();
//        if(!"2".equals(currentUser.getUser().getUserLevel())){
//            return AjaxResult.error("非站点不可使用设备管理");
//        }
        //stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        //stationDeviceManage.setStationName(currentUser.getUser().getDept().getDeptName());
        if(stationDeviceManage.getStationId()==null){
            return AjaxResult.error("油站信息错误");
        }
        if(stationDeviceManage.getUserIdList()!=null&&stationDeviceManage.getUserIdList().size()>0){
            stationDeviceManage.setUserIds(String.join(",",stationDeviceManage.getUserIdList()));
        }
        if(stationDeviceManage.getGunNoList()!=null&&stationDeviceManage.getGunNoList().size()>0){
            stationDeviceManage.setGunNo(String.join(",",stationDeviceManage.getGunNoList()));
        }
        //云喇叭
        if("4".equals(stationDeviceManage.getDeviceType())){
            stationDeviceManage.setDeviceFactory("4");
        }
        // 新款K4
        if("3".equals(stationDeviceManage.getDeviceFactory())){
            stationDeviceManage.setDeviceType("3");
        }
        return toAjax(stationDeviceManageService.insertStationDeviceManage(stationDeviceManage));
    }

    @GetMapping("/setVoice")
    public void setVoice(@RequestBody StationDeviceManage stationDeviceManage) throws InterruptedException {
        Methods m= Methods.getInstance();
        m.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
        stationDeviceAudioService.setVoice(stationDeviceManage,m);
    }

    @GetMapping("/getK4Status")
    public AjaxResult getK4Status(@RequestBody StationDeviceManage stationDeviceManage){
        Methods m= Methods.getInstance();
        m.init(stationDeviceManage.getClientId(), stationDeviceManage.getClientSecret());
        stationDeviceManageService.checkStatus(stationDeviceManage,m);
        return null;
    }

    /**
     * 修改油站设备管理
     */
    @PutMapping
    @ApiOperation("修改设备")
    public AjaxResult edit(@RequestBody StationDeviceManage stationDeviceManage)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        //stationDeviceManage.setStationId(currentUser.getUser().getStationId());
        if(stationDeviceManage.getUserIdList()!=null&&stationDeviceManage.getUserIdList().size()>0){
            stationDeviceManage.setUserIds(String.join(",",stationDeviceManage.getUserIdList()));
        }
        if(stationDeviceManage.getUserIdList()!=null&&stationDeviceManage.getUserIdList().size()>0){
            stationDeviceManage.setUserIds(String.join(",",stationDeviceManage.getUserIdList()));
        }
        //stationDeviceManage.setStationName(currentUser.getUser().getDept().getDeptName());
        return toAjax(stationDeviceManageService.updateStationDeviceManage(stationDeviceManage));
    }

    /**
     * 删除油站设备管理
     */
    @PostMapping("/delete")
    @ApiOperation("删除设备")
    public AjaxResult remove(@RequestBody List<Long> deviceIds)
    {
        Long[] longs = deviceIds.stream().toArray(Long[]::new);
        return toAjax(stationDeviceManageService.deleteStationDeviceManageByIds(longs));
    }

    /**
     * 状态修改
     */
    @PutMapping("/changeManageStatus")
    public AjaxResult changeManageStatus(@RequestBody StationDeviceManage stationDeviceManage)
    {
        return toAjax(stationDeviceManageService.updateStationDeviceManage(stationDeviceManage));
    }
}
